package com.sxdz.controller.task.reconciliation

import com.sxdz.constant.CommonConstant
import com.sxdz.constant.GlobalConstant
import com.sxdz.controller.service.order.IOrderService
import com.sxdz.models.TOrder
import com.sxdz.models.common.Order
import com.toolbox.utils.DateUtil
import groovy.transform.CompileStatic
import groovy.transform.TypeChecked
import org.apache.commons.net.ftp.FTPClient
import org.apache.commons.net.ftp.FTPReply
import org.slf4j.Logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

import java.text.SimpleDateFormat

/**
 * Created by lzw on 2016/8/24.
 */
@CompileStatic
@TypeChecked
@Component("reconciliation")
class Reconciliation {

    @Autowired
    private IOrderService orderService

    private Logger logger = org.slf4j.LoggerFactory.getLogger(Reconciliation.class)

    private FTPClient ftp;
    /**
     * 每天生产定时生成对账文件并推送广电ftp
     */
    void main() {
        try {
            String filePath = GlobalConstant.getString("reconciliation_filePath")
            String fileName = DateUtil.getDateYesterday() + ".txt";
            FileWriter fileWriter = new FileWriter(filePath + fileName, true);
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd")
            Date dt = format.parse(DateUtil.getDateYesterday().trim())
            Long btime = DateUtil.dateFirst(dt)
            Long etime = DateUtil.dateLast(dt)
            Map<String, Object> params = [:]
            params << [startTime: btime]
            params << [endTime: etime]
            params << [payStatus: CommonConstant.PayStatus.PaySuccess.value] //支付成功
            params << [isActive: CommonConstant.IsActive.True.value]
            List<TOrder> orderList = orderService.findListByParams(params, Order.asc("create_time"))
            StringBuffer buffer = new StringBuffer();
            buffer.append("intelligentNo|payFee|payTime|payStatus|transactionId|bossResult|bossNo\r\n")
            long total_account = 0
            int total_num = 0
            if (orderList != null && orderList.size() > 0) {
                total_num = orderList.size()
                for (TOrder order : orderList) {
                    buffer.append(order.intelligentNo).append("|")
                    buffer.append(order.payFee).append("|")
                    buffer.append(order.payTime).append("|")
                    buffer.append(order.payStatus).append("|")
                    buffer.append(order.transactionId).append("|")
                    buffer.append(order.gdResult).append("|")
                    buffer.append(order.gdSerialNo + "\r\n")
                    total_account += order.payFee
                }
            }
            buffer.append(total_num + "|" + total_account)
            fileWriter.write(buffer.toString());
            fileWriter.flush();
            fileWriter.close();
            logger.info("生成对账文件：" + fileName)
            //上传文件
            String ftpPath=GlobalConstant.getString("ftpPath")
            String ftpIp=GlobalConstant.getString("ftpIp")
            String ftpPort=GlobalConstant.getString("ftpPort")
            String ftpUserName=GlobalConstant.getString("ftpUserName")
            String ftpPasswd=GlobalConstant.getString("ftpPasswd")
            boolean isConn=false;
                for (int i=0;i<3;i++){//最多连接三次
                    isConn=connect(ftpPath, ftpIp, Integer.parseInt(ftpPort), ftpUserName,ftpPasswd);
                    if(isConn){
                        break;
                    }
            }
            if(isConn){
                File file=new File(filePath+fileName);
                upload(file);
                logger.info("上传对账文件成功"+fileName)
            }else {
                logger.info("上传对账文件失败,连接超时")
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生成对账文件失败：", e.getStackTrace())
        } finally {

        }

    }

/**
 *
 * @param path 上传到ftp服务器哪个路径下
 * @param addr 地址
 * @param port 端口号
 * @param username 用户名
 * @param password 密码
 * @return
 * @throws Exception
 */
    private  boolean connect(String path,String addr,int port,String username,String password) throws Exception {
        try{
            boolean result = false;
            ftp = new FTPClient();
            int reply;
            ftp.connect(addr,port);
            ftp.login(username,password);
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return result;
            }
            ftp.changeWorkingDirectory(path);
            result = true;
            return result;
        }catch (Exception e){
            logger.error("ftp连接失败：", e.getStackTrace())
            return false;
        }

    }
    /**
     *
     * @param file 上传的文件或文件夹
     * @throws Exception
     */
    private void upload(File file) throws Exception{
        if(file.isDirectory()){
            ftp.makeDirectory(file.getName());
            ftp.changeWorkingDirectory(file.getName());
            String[] files = file.list();
            for (int i = 0; i < files.length; i++) {
                File file1 = new File(file.getPath()+"\\"+files[i] );
                if(file1.isDirectory()){
                    upload(file1);
                    ftp.changeToParentDirectory();
                }else{
                    File file2 = new File(file.getPath()+"\\"+files[i]);
                    FileInputStream input = new FileInputStream(file2);
                    ftp.storeFile(file2.getName(), input);
                    input.close();
                }
            }
        }else{
            File file2 = new File(file.getPath());
            FileInputStream input = new FileInputStream(file2);
            ftp.storeFile(file2.getName(), input);
            input.close();
        }
    }


}
